"""
权限管理模块
提供权限检查的便捷函数和依赖注入
注意：实际的权限检查逻辑统一在 app.services.permission_service 中实现
"""
from typing import List
from fastapi import Depends, HTTPException, status  # pyright: ignore[reportMissingImports]
from fastapi.security import OAuth2PasswordBearer  # pyright: ignore[reportMissingImports]
from .security import verify_token
from ..models.user import UserRole
from ..services.permission_service import PermissionService, Permissions

# 向后兼容：导出权限常量
__all__ = ['get_current_user', 'require_permission', 'check_permissions', 'check_roles', 
           'Permissions', 'oauth2_scheme']

# OAuth2密码承载令牌
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")

def get_current_user(token: str = Depends(oauth2_scheme)):
    """
    获取当前用户（已废弃，请使用 app.api.deps.get_current_user）
    保留此函数以保持向后兼容性
    """
    payload = verify_token(token)
    return payload

def has_permission(user, permission: str) -> bool:
    """
    检查用户是否拥有指定权限（已废弃，请使用 PermissionService.has_permission）
    保留此函数以保持向后兼容性
    """
    return PermissionService.has_permission(user, permission)

def require_permission(user, permission: str):
    """
    要求用户拥有指定权限，否则抛出异常
    使用 PermissionService 进行权限检查
    
    Args:
        user: 用户信息字典
        permission: 需要的权限字符串
        
    Raises:
        HTTPException: 如果用户没有权限，抛出403错误
    """
    import logging
    logger = logging.getLogger(__name__)
    
    has_perm = PermissionService.has_permission(user, permission)
    
    if not has_perm:
        user_email = user.get('email', 'unknown')
        logger.warning(f"Permission denied: user={user_email}, permission={permission}")
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=f"权限不足: 需要 {permission} 权限"
        )

def check_permissions(required_permissions: List[str] = None):
    """
    检查用户是否拥有所需权限（已废弃，请使用 app.api.deps.check_permissions）
    保留此函数以保持向后兼容性
    """
    def permission_checker(current_user: dict = Depends(get_current_user)):
        if not required_permissions:
            return current_user
        
        # 使用 PermissionService 检查权限
        if not PermissionService.has_permissions(current_user, required_permissions):
            missing_permissions = [p for p in required_permissions 
                                 if not PermissionService.has_permission(current_user, p)]
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"权限不足: 需要 {', '.join(missing_permissions)} 权限"
            )
        
        return current_user
    
    return permission_checker

def check_roles(required_roles: List[UserRole] = None):
    """
    检查用户是否拥有所需角色（已废弃，请使用 app.api.deps.check_roles）
    保留此函数以保持向后兼容性
    """
    def role_checker(current_user: dict = Depends(get_current_user)):
        if not required_roles:
            return current_user
        
        # 使用 PermissionService 检查角色
        role_strings = [role.value for role in required_roles]
        if not PermissionService.has_roles(current_user, role_strings):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"角色不足: 需要 {', '.join(role_strings)} 角色"
            )
        
        return current_user
    
    return role_checker

def get_permissions_for_role(role: UserRole) -> List[str]:
    """获取角色对应的权限列表"""
    return PermissionService.get_permissions_for_role(role)
